export default {
	// 开启命名空间
	namespaced: true,
	state: {
		 // 购物车的数组，用来存储购物车中每个商品的信息对象
		 // 每个商品的信息对象，都包含如下 6 个属性：
		 // { goods_id, goods_name, goods_price, goods_count,goods_small_logo, goods_state} 
		cart: JSON.parse(uni.getStorageSync("cart") || "[]")
	},
	actions: {},
	mutations: {
		// 加入购物车的 mutation 
		addToCart(state,goods) {
			let findRessult= state.cart.find(item=> item.goods_id===goods.goods_id);
			// 购物车中没有指定商品
			if(!findRessult) {
				state.cart.push(goods);
			}else {
				// 购物车中有指定商品，让商品数量加一
				findRessult.goods_count++;
			}
			// 通过commit，调用countAbout命名空间小的saveToStorage方法持久化存储购物车数据
			this.commit("cartAbout/saveToStorage")
		},
		// 持久化存储 cart 购物车数据的mutation
		saveToStorage(state) {
			uni.setStorageSync("cart",JSON.stringify(state.cart));
		},
		// 改变商品勾选状态的mutation
		updateGoodsState(state,goodsObj) {
			let findResult= state.cart.find(item=> item.goods_id===goodsObj.goods_id);
			if(findResult) {
				findResult.goods_state=!goodsObj.goods_state;
				this.commit("cartAbout/saveToStorage");
			}
		},
		// 改变商品数量的mutation
		updateGoodsCount(state,goodsObj) {
			let findResult= state.cart.find(item=> item.goods_id===goodsObj.goods_id);
			if(findResult) {
				findResult.goods_count=goodsObj.goods_count;
			}
			this.commit("cartAbout/saveToStorage");
		},
		// 滑动删除商品的mutation
		deleteGoodsById(state,goodsObj) {
			state.cart= state.cart.filter(item=> item.goods_id!==goodsObj.goods_id);
			this.commit("cartAbout/saveToStorage");
		},
		// 点击全选按钮的mutation
		updateAllChecked(state,checked) {
			state.cart.forEach(item=> item.goods_state=checked);
			this.commit("cartAbout/saveToStorage");
		}
	},
	getters: {
		// 商品的总量
		total(state) {
			let count=0;
			state.cart.forEach(item=> count+=item.goods_count);
			return count;
		},
		// 选中商品的总量
		checkedCount(state) {
			return state.cart.filter(item=> item.goods_state).reduce((count,item)=> count+=item.goods_count,0);
		},
		// 选中商品的总价
		checkedAmount(state) {
			return state.cart.filter(item=> item.goods_state).reduce((total,item)=> total+=item.goods_price*item.goods_count,0).toFixed(2);
		}
	}
}